package com.htgd.gardenexpo.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

@RestController
@RequestMapping("/utils/apiMap")
@Api(tags = "Api地图")
@Slf4j
public class ApiMap {

    private String key = "ORLBZ-UFVWV-BXUP4-5EGJH-PQPDK-QEB2F";

    @GetMapping("/directionWalking")
    @ApiOperation("线路规划-步行")
    public  String directionWalking(String from,String to) {
        String res = "";
        JSONObject jsonObject = new JSONObject();
        try {
            // 创建URL对象并设置API的请求URL
            URL url = new URL("https://apis.map.qq.com/ws/direction/v1/walking/?from="+from+"&to="+to+"&output=json&callback=cb&key="+key);

            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法
            connection.setRequestMethod("GET");

            // 获取输入流并读取数据
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();

            // 关闭连接
            connection.disconnect();

            // 处理JSON数据
            jsonObject = JSON.parseObject(response.toString());
            JSONObject result = jsonObject.getJSONObject("result");
            JSONArray routes = result.getJSONArray("routes");
            JSONObject jsonObject1 = jsonObject.parseObject(routes.get(0).toString());
            JSONArray polyline = jsonObject1.getJSONArray("polyline");
            res = polyline.toString();
        }catch (Exception e){
            e.printStackTrace();
        }
        return res;
    }
}
